package com.yang.news.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yang.news.convert.HotSearchConvert;
import com.yang.news.dao.entity.HotSearchRecord;
import com.yang.news.dao.mapper.HotSearchRecordMapper;
import com.yang.news.model.dto.HotSearchDTO;
import com.yang.news.model.page.Page;
import com.yang.news.service.HotSearchRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Billyang
 * @date 2024/9/3 11:41
 */
@Slf4j
@Service
public class HotSearchRecordServiceImpl extends ServiceImpl<HotSearchRecordMapper, HotSearchRecord>
        implements HotSearchRecordService {
    @Override
    public Boolean batchSave(List<HotSearchRecord> hotSearchRecordList) {
        if (CollectionUtils.isEmpty(hotSearchRecordList)) {
            return true;
        }

        List<String> searchIdList = hotSearchRecordList.stream().map(HotSearchRecord::getHotSearchId).collect(Collectors.toList());
        List<HotSearchRecord> existList = this.lambdaQuery().in(HotSearchRecord::getHotSearchId, searchIdList).list();
        if (!CollectionUtils.isEmpty(existList)) {
            List<String> existSearchIdList = existList.stream().map(HotSearchRecord::getHotSearchId).collect(Collectors.toList());
            hotSearchRecordList.removeIf(hotSearchRecord -> existSearchIdList.contains(hotSearchRecord.getHotSearchId()));
        }

        if (CollectionUtils.isEmpty(hotSearchRecordList)) {
            return true;
        }
        log.info("待插入数据数量：{}", hotSearchRecordList.size());
        return this.saveBatch(hotSearchRecordList);
    }

    @Override
    public List<HotSearchRecord> queryTodayByType(String type) {
        Date now = new Date();
        return this.lambdaQuery().eq(HotSearchRecord::getHotSearchResource, type).ge(HotSearchRecord::getCreateTime, DateUtil.beginOfDay(now)).list();
    }

    @Override
    public Page<HotSearchDTO> pageQueryHotSearchByTitle(String title, Integer pageNum, Integer pageSize) {
        //设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        //查询热搜
        List<HotSearchRecord> hotSearchRecordList = this.list(
                new QueryWrapper<HotSearchRecord>().lambda().like(HotSearchRecord::getHotSearchTitle, "%" + title + "%")
                        .orderByDesc(HotSearchRecord::getCreateTime));
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(hotSearchRecordList)) {
            return Page.emptyPage();
        }
        //对象转换
        return Page.resetPage(hotSearchRecordList, hotSearchRecordList.stream().map(HotSearchConvert::toDTOWhenQuery)
                .collect(Collectors.toList()));
    }
}
